/* 系统公用方法 */
(function(win, doc) {
    var host = "";
    var admin = {
        serviceName: "pages",
        api: host + "/api/",
        basePath: function() {
            var curWwwPath = window.document.location.href;
            var pathName = window.document.location.pathname;
            var pos = curWwwPath.indexOf(pathName);
            var localhostPath = curWwwPath.substring(0, pos);
            var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
            var path = localhostPath + projectName + "/";
            return path;
        },
        screen:function () {
            var w = $(window).width();
            return w >= 1200 ? 3 : w >= 992 ? 2 : w >= 768 ? 1 : 0;
        },
        //获取公司年月日（2014-xxxx）
        copyrightYear:function(id){
            var copyrightYear=new Date().getFullYear();
            if(copyrightYear<2014){$(id).html(copyrightYear +"-2014");}
            else if(copyrightYear==2014){$(id).html(copyrightYear);}
            else{$(id).html("2014-"+copyrightYear);}
        },
        //返回首页Tab
        goHome:function (o,refresh) {
            var type = $(o).data("type");
            if(type=="ajax"){
                $(document).data("tabs").create({ url: $(o).data("href") }, true);
                if(refresh){
                    parent.$(".tabs-show-refresh-tab").trigger("click");     
                }   
            }else if(type=="iframe"){
                parent.$(parent.document).data("tabs").create({ url: $(o).data("href") }, true);
                if(refresh){
                    parent.$(".tabs-show-refresh-tab").trigger("click");     
                }     
            }else{
                alert("类型错误，请检查！")
            }
        },
        //打开指定Tab
        openTabs:function (o,refresh) {
            var type = $(o).data("type"),
            title = $(o).data("title"),url=$(o).data("href");
            if(type=="ajax"){
                $(document).data("tabs").create({ 
                    iframe: type,
                    title: title, 
                    url: url 
                }, true); 
                if(refresh){
                    parent.$(".tabs-show-refresh-tab").trigger("click");     
                }
            }else if(type=="iframe"){
                if(parent.$(parent.document).data("tabs")!=undefined){
                    parent.$(parent.document).data("tabs").create({ 
                        iframe: type,
                        title: title, 
                        url: url 
                        }, true);
                        if(refresh){
                            parent.$(".tabs-show-refresh-tab").trigger("click");     
                        }
                }else{
                    console.log(url)
                    window.open(admin.basePath()+"/"+url)
                }
                
            }else{
                alert("参数类型错误，请检查！");
            }
        },
        //关闭当前Table
        closeTabs:function (o) {
            var type = $(o).data("type");
             if(type=="ajax"){
                layer.close(layer.index);
                 if($("#tabs-nav-panel .nav-tabs li").size()>1){
                    $(document).data("tabs").close($("#tabs-nav-panel .nav-tabs li.active"));
                 }
                 
             }else if(type=="iframe"){
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index); 
                if($("#tabs-nav-panel .nav-tabs li").size()>1){
                    parent.$(parent.document).data("tabs").close(parent.$("#tabs-nav-panel .nav-tabs li.active"));
                }
             }else{
                layer.close(layer.index)
                alert("类型错误，请检查！");
             }
        },
        //table查询
        tableSearch:function (id) {
            $(id).bootstrapTable('refreshOptions',{pageNumber:1});
            $(id).bootstrapTable('refresh');
        },
        //table 数据
        tableServer :function(tableId, columns, url,headersUrl,queryParams,responseHandler,data) {
            $(tableId).bootstrapTable('destroy').bootstrapTable({
              url: url,
              crossDomain: true,
              ajaxOptions: {
                headers: {
                  "url": headersUrl
                },
                xhrFields: {
                  withCredentials: true
                },
                beforeSend: function(request) {
                    console.log("加载前")
                }
              },
              onLoadSuccess: function(data) {
                console.log("完成")
              },
              contentType: "application/json",
              method: 'post',
              cache: false,
              pageNumber: 1,
              pagination: true,
              sidePagination: 'server',
              pageSize: 10, 
              pageList: [10, 20, 50],
              paginationLoop: false,
              queryParamsType: 'limit',
              queryParams: queryParams,
              columns: columns,
              responseHandler:responseHandler
            });
        },
        tableAjax :function(tableId, columns, url,queryParams,responseHandler) {
            $(tableId).bootstrapTable('destroy').bootstrapTable({
              contentType: "application/json",
              method: 'post',
              url:url,
              pageNumber: 1, //初始化加载第一页，默认第一页
              pagination: true, //是否分页
              sidePagination: 'server', //指定服务器端分页
              pageSize: 10, //单页记录数
              pageList: [10, 20, 50], //分页步进值
              paginationLoop: false,
              queryParamsType: 'limit', //查询参数组织方式
              queryParams: queryParams,//请求服务器时所传的参数
              columns: columns,//列表
              responseHandler:responseHandler
            });
        },
        //获取table checkbox 选中长度
        getTableCheck: function (id) {
            return $.map(
              $(id).bootstrapTable("getSelections"),
              function (row) {
                return row.id;
              }
            );
        },
        //根据table checkbox 选中长度判断按钮disabled 状态
        isBtnsDisabled: function (obj,tableId) {
            if (admin.getTableCheck(tableId).length > 0) {
              $(obj).removeAttr("disabled")
            } else {
              $(obj).attr("disabled", true)
            }
        },
        //删除/停用/启用/上线/下线操作
        handle: function (o, tableId, fn) {
            var type = $(o).data("type");
            var title = $(o).data("title");
            var name = $(o).data("name");
            if(typeof name === "undefined"){
                name=="";
            }else{
                name = $(o).data("name")
            }
            if (type == "batch") {
                var datas = JSON.stringify({
                    "ids": admin.getTableCheck(tableId)
                });
                parent.layer.confirm(
                    "确认要<strong class='pad-hor text-danger'>"+title+"</strong>选中的记录吗？", {
                    closeBtn: 0,
                    title: "系统提示",
                    shade: [0.1, "#000"]
                },
                function (index) {
                    parent.layer.close(index);
                    if (fn != "" && $.isFunction(fn)) fn();
                    }
                );
            } else {
                var datas = JSON.stringify({
                    "ids": $(o).data("id")
                });
                parent.layer.confirm(
                    "确认要<strong class='pad-hor text-danger'>"+title+" "+name+" </strong>此条记录吗？", {
                    closeBtn: 0,
                    title: "系统提示",
                    shade: [0.1, "#000"]
                },
                function (index) {
                    parent.layer.close(index);
                    if (fn != "" && $.isFunction(fn)) fn();
                    }
                );
            }
            console.log(datas) 
        },
        //打开外链
        iframeLink: function (o) {
            var index = layer.getFrameIndex(window.name);
            var w = $(o).data("width") ? $(o).data("width") : $(window.parent.window).width()*0.9,
            h = $(o).data("height") ? $(o).data("height") : $(window.parent.window).height()*0.9;
            var title = $(o).data("title"),
            url = $(o).data("href");
            var  closeBtn = $(o).data("closebtn");
            if(closeBtn==undefined||closeBtn==true){
                closeBtn = 1
            }else{
                closeBtn=0
            }
            var  maxmin = $(o).data("maxmin");
            if(maxmin==undefined||maxmin==true){
                maxmin = true
            }else{
                maxmin = false
            }
          parent.layer.open({
            type: 2,
            title: title,
            closeBtn:closeBtn,
            maxmin: maxmin,
            area: admin.screen() < 2 ? ['94%', '94%'] : [w + "px", h + "px"],
            content: [ url, "yes"]
          });
        },
        //系统内部
        iframe: function (o) {
            var layer =window.layer;
            //var index = layer.getFrameIndex(window.parent.window.name);
            var index = layer.getFrameIndex();
            var w = $(o).data("width") ? $(o).data("width") : $(window.parent.window).width()*0.9,
            h = $(o).data("height") ? $(o).data("height") : $(window.parent.window).height()*0.9;
            var title = $(o).data("title"),
            url = $(o).data("href")?$(o).data("href"):$(o).data("url"),
            t = (new Date()).valueOf();
            if((url.indexOf("?")>=0)){
                url = url + "&t=" + t;
            }else{
                url = url + "?t=" + t;
            }
            var  closeBtn = $(o).data("closebtn");
            if(closeBtn==undefined||closeBtn==true){
                closeBtn = 1
            }else{
                closeBtn=0
            }
            var  maxmin = $(o).data("maxmin");
            if(maxmin==undefined||maxmin==true){
                maxmin = true
            }else{
                maxmin = false
            }
            
            layer.open({
                type: 2,
                title: title,
                closeBtn:closeBtn,
                maxmin: maxmin,
                area: admin.screen() < 2 ? ['94%', '94%'] : [w + "px", h + "px"],
                content: [url, "yes"],
                success: function (layero, index) {
                //parent.layer.full(index)
                //parent.layer.iframeAuto(index);
                }
            });
        },
        //系统内部
        ajaxDialog: function (o) {
            var layer =window.layer;
            var index = layer.getFrameIndex();
            var w = $(o).data("width") ? $(o).data("width") : $(window).width()*0.5,
            h = $(o).data("height") ? $(o).data("height") : $(window).height()*0.9;
            var auto=$(o).data("auto");
            var title = $(o).data("title"),
            url = $(o).data("href")?$(o).data("href"):$(o).data("url"),
            t = (new Date()).valueOf();
            if((url.indexOf("?")>=0)){
                url = url + "&t=" + t;
            }else{
                url = url + "?t=" + t;
            }
            var  closeBtn = $(o).data("closebtn");
            if(closeBtn==undefined||closeBtn==true){
                closeBtn = 1
            }else{
                closeBtn=0
            }
            var  maxmin = $(o).data("maxmin");
            if(maxmin==undefined||maxmin==true){
                maxmin = true
            }else{
                maxmin = false
            }
            $.get(url, function(res){
                layer.open({
                    shade:$(o).data("shade")==0?0:0.3,
                    id:$(o).data("id"),
                    type: 1,
                    title: title,
                    closeBtn:closeBtn,
                    maxmin: maxmin,
                    area: admin.screen() < 2 ? ['94%', '94%'] : auto ? ["auto","auto"] : [w + "px", h + "px"],
                    content: res
                });
            });
            
        },
        //表单提交
        ajaxForm:function(formId, url, o, fn) {
            if ($(formId).valid()) {
                var datas = JSON.stringify($(formId).serializeJSON());
                $.ajax({
                    type: 'POST',
                    xhrFields: {
                        withCredentials: true
                    },
                    crossDomain: true,
                    async: true,
                    url: portalUrl,
                    dataType: 'json',
                    data: datas,
                    contentType: "application/json",
                    timeout: 30000,
                    beforeSend: function (request) {
                        request.setRequestHeader("token", token);
                        request.setRequestHeader("url", url);
                        request.setRequestHeader("x-requested-with", "XMLHttpRequest");
                    },
                    success: function (data) {
                        var code = data.code,
                            msg = data.msg;
                        if (data.code === 0) {
                            if (fn != "" && $.isFunction(fn)) fn(data);
                        } else {
                            $(o).removeAttr("disabled").html("保存");
                        }
                    }
                });
            }
        },
        //日期控件处理  // obj obj 日期输入框 dobubble  是否为双日期（true） second 有无时分（有则true）
        calenders:function(obj,dobubble,second){
            var singleNot,formatDate,calendersRanges;
            if(dobubble ==true){
                singleNot = false;
                calendersRanges = {
                    '昨日': [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')],
                    '今日': [moment().startOf('day'), moment()],
                    '最近7日': [moment().subtract(6, 'days'), moment()],
                    '本月': [moment().startOf("month"), moment().endOf("month")],
                    '最近30日': [moment().subtract(29, 'days'), moment()],
                    '上个月': [moment().subtract(1, "month").startOf("month"), moment().subtract(1, "month").endOf("month")],
                    '最近三个月': [moment().subtract(3, "month").startOf("month"), moment().endOf("month")]
                }
            }else{
                singleNot = true;
                calendersRanges = {
                    '昨日': [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')],
                    '今日': [moment().startOf('day'), moment()]
                }
            }
            if(second ==true){
                formatDate = "YYYY-MM-DD HH:mm";
            }else{
                formatDate = "YYYY-MM-DD";
            }
            var calendersLocale = {
                format:formatDate,
                applyLabel: "确定",
                cancelLabel: "取消",
                fromLabel: "起始时间",
                toLabel: "结束时间",
                customRangeLabel: "自定义",
                daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
                monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
                firstDay: 1
            }
            $(obj).daterangepicker({
                "ranges":calendersRanges,
                "singleDatePicker": singleNot,
                "timePicker": second,
                "timePicker24Hour": second,
                "timePickerSeconds": false,
                "showDropdowns":true,
                "timePickerIncrement" :1,
                "linkedCalendars": false,
                "autoApply":true,
                "autoUpdateInput":false, 
                "alwaysShowCalendars": true,
                "opens":"right",
                "buttonClasses": ['btn btn-default'],
                "applyClass": 'btn-small btn-primary blue',
                "cancelClass": 'btn-small',
                "locale":calendersLocale
            }, function(start,end) {
                if(second ==true&&dobubble ==true){
                    //双日历 日期 + 时分
                    $(obj).val($.trim(start.format('YYYY-MM-DD HH:mm')+' - '+end.format('YYYY-MM-DD HH:mm')));
                    $(obj).next().val(start.format('YYYY-MM-DD HH:mm')).next().val(end.format('YYYY-MM-DD HH:mm'));
                }else if(second ==false&&dobubble ==true){
                    //双日历 日期
                    $(obj).val($.trim(start.format('YYYY-MM-DD')+' - '+ end.format('YYYY-MM-DD')));
                    $(obj).next().val(start.format('YYYY-MM-DD')).next().val(end.format('YYYY-MM-DD'));
                }else if(second ==false&&dobubble ==false){
                    //单日历 日期
                     $(obj).val(start.format('YYYY-MM-DD'));
                }else if(second ==true&&dobubble ==false){
                    //单日历 日期 + 时分
                    $(obj).val(start.format('YYYY-MM-DD HH:mm'));
                }
            });
            //清空
            $(obj).on('cancel.daterangepicker', function (ev, picker) {
             $(this).val('').next().val("").next().val("");
            });
        },
        //数字转换为大写
        digitUppercase: function(n) {
            var fraction = ['角', '分'];
            var digit = [
                '零', '壹', '贰', '叁', '肆',
                '伍', '陆', '柒', '捌', '玖'
            ];
            var unit = [
                ['元', '万', '亿'],
                ['', '拾', '佰', '仟']
            ];
            var head = n < 0 ? '欠' : '';
            n = Math.abs(n);
            var s = '';
            for (var i = 0; i < fraction.length; i++) {
                s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
            }
            s = s || '整';
            n = Math.floor(n);
            for (var i = 0; i < unit[0].length && n > 0; i++) {
                var p = '';
                for (var j = 0; j < unit[1].length && n > 0; j++) {
                    p = digit[n % 10] + unit[1][j] + p;
                    n = Math.floor(n / 10);
                }
                s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
            }
            return head + s.replace(/(零.)*零元/, '元')
                .replace(/(零.)+/g, '零')
                .replace(/^整$/, '零元整');
        },
        //替换html
        htmlReplace: function(str) {
            str = str.replace(/&/g, '＆');
            str = str.replace(/</g, '＜');
            str = str.replace(/>/g, '＞');
            str = str.replace(/\!/g, '！');
            str = str.replace(/\|/g, '｜');
            str = str.replace(/\./g, '．');
            str = str.replace(/\^/g, '＾');
            str = str.replace(/\$/g, '＄');
            str = str.replace(/\&/g, '＆');
            str = str.replace(/\*/g, '＊');
            str = str.replace(/=/g, '＝');
            return str;
        },
        //截取长度
        cutstr: function(str, len) {
            var str_length = 0;
            var str_len = 0;
            var str_cut = new String();
            var str_len = str.length;
            for (var i = 0; i < str_len; i++) {
                var a = str.charAt(i);
                str_length++;
                if (escape(a).length > 4) {
                    str_length++;
                }
                str_cut = str_cut.concat(a);
                if (str_length >= len) {
                    str_cut = str_cut.concat("...");
                    return str_cut;
                }
            }
            if (str_length < len) {
                return str;
            }
        },
        strTobool: function(str) {
            return (str && typeof str == 'string') ? (str.toLowerCase() == 'true' || str == '1') : (str == true);
        },
        //获取地址 避免地址混乱
        getRootPath: function() {
            //point根据项目目录自己设定
            var location = win.location.href,
                path = location.split(app.serviceName)[0] + app.serviceName;
            return path;
        },
        //获取URL参数 key 参数名称 url URL链接，默认为当前URL
        getUrlKey: function(key, url) {
            var url = url ? url : location.href;
            var v = '';
            var o = url.indexOf(key + "=");
            if (o != -1) {
                o += key.length + 1;
                e = url.indexOf("&", o);
                if (e == -1) {
                    e = url.length;
                }
                //v = decodeURIComponent(url.substring(o, e));
                v = url.substring(o, e);
            }
            return v;
        },
        //计时
        countTime: function(o,fn) {
            $(o).each(function() {
                var endtime = new Date($(this).attr("endtime")).getTime();
                var nowtime = new Date().getTime();
                var youtime = endtime - nowtime;
                var seconds = Math.floor(youtime / 1000);
                var minutes = Math.floor(seconds / 60);
                var hours = Math.floor(minutes / 60);
                var days = Math.floor(hours / 24);
                var CDay = days;
                var CHour = Math.floor(hours % 24);
                var CMinute = Math.floor(minutes % 60);
                var CSecond = Math.floor(seconds % 60);
                if (CDay < 10) { CDay = "0" + CDay; }
                if (CHour < 10) { CHour = "0" + CHour; }
                if (CMinute < 10) { CMinute = "0" + CMinute; }
                if (CSecond < 10) { CSecond = "0" + CSecond; }
                if (endtime <= nowtime) {
                    $(this).hide();
                    $(this).next().hide();
                    $(this).html("<span class='countTimeExp'>&nbsp;</span>");
                    console.log("倒计时完毕");
                    if (fn != "" && $.isFunction(fn)) fn();
                    return false;
                } else {
                    if ($(this).attr("showDate") == "yes") {
                        $(this).html("<span class='countTimeBox'><em>倒计时</em></span><span class='countDay'>" + days + "</span><em>天</em><span class='countHour'>" + CHour + "</span><em>:</em><span class='countMinu'>" + CMinute + "</span><em>:</em><span class='countSec'>" + CSecond + "</span>");
                    } else {
                        $(this).html("<span class='countTimeBox'><em>倒计时</em></span><span class='countHour'>" + CHour + "</span><em>:</em><span class='countMinu'>" + CMinute + "</span><em>:</em><span class='countSec'>" + CSecond + "</span>");
                    }
                }
            });
            setTimeout(function() {
                admin.countTime(o,fn)
            }, 1000);
        },
        //获取全部cookies
        getAllCookies: function() {
            if (document.cookie) {
                var aCookie = document.cookie.split(";");
                var re = "";
                for (var i = 0; i < aCookie.length; i++) {
                    var aCrumb = aCookie[i].split("=");
                    re += (aCrumb[0] + ":" + aCrumb[1] + '\n');
                }
                return re;
            } else {
                return "无cookie"
            }
        },
        //是否支持cookies
        isCookie: function() {
            if (window.navigator.cookieEnabled) {
                return true;
            } else {
                return false;
            }
        },
        //是否支付本地缓存
        isLocalStorage: function() {
            if (window.localStorage) {
                return true;
            } else {
                return false;
            }
        },
        error:function(info){
            $(document).data("tabs").close($("#tabs-nav-panel .nav-tabs li.active"));
            // $(document).data("tabs").create({ 
            //     iframe: false,
            //     title: "系统提示", 
            //     url: "404.html" 
            // }, true); 
            layer.msg(info)
        }
    };
    win.admin = admin;
}(window, document));

$(function(){
     $.ajaxSetup({
        contentType:"application/x-www-form-urlencoded;charset=utf-8",
        timeout:20000,
        error:function(xhr, textStatus){
            console.log(xhr);
            console.log(textStatus);
            return false;
            if(xhr.status == 2000){//session超时
                alert("session超时");
                parent.window.location.href = getPath('/index');
                return;
            }else if (xhr.status == 404) {
                admin.error("您访问的页面已经删除或者不存在")
                return;
            } else if (xhr.status == 500) {
                alert("服务器内部错误");
                return;
            }
            if(textStatus=="error"){
                layer.msg("登陆超时！请重新登陆！")
                parent.window.location.href = getPath('/index');
            }else if(textStatus==400){
                alert("请求不存在。");
            }
        },
        complete:function(xhr,textStatus){
            $("#admin-loading").hide();
            return false;
            if(xhr.status == 2000){//session超时
                alert("session超时");
                parent.window.location.href = getPath('/index');
                return;
            }else if (xhr.status == 404) {
                admin.error("您访问的页面已经删除或者不存在");
                return;
            } else if (xhr.status == 500) {
                alert("服务器内部错误");
                return;
            }
            if(textStatus=="error"){
                layer.msg("登陆超时！请重新登陆！")
                parent.window.location.href = getPath('/index');
            }else if(textStatus==400){
                alert("请求不存在。");
            }
        }
     });
     admin.copyrightYear("#copyrightYear");
 });



 /*
*@param s 即将被转化的字符  String
*@param num 字符的间隔    Number
*@param type 字符的类型  String
*/
function getSpace(s,num,type){
    //过滤了空格的存在
    //实际中根据需求是否必须去掉空格
    s = s.replace(/\s*/g,'');
    if(s.length === 0){
        return '';
    }
    if(s.length < num && s.length !== 0){
        return s;
    }
    var m,n,res = '';
    var reg = new RegExp('(\\w{'+num+'})','g');
    var reg2 = new RegExp('(?:\\w{'+num+'})+(\\w+)','g');
    var reg3 = new RegExp(''+type+'$');
    while(m = reg.exec(s)){
        res += m[1] + type;
    }
    if(s.length%num == 0){
        return res.replace(reg3,'');
    }else{
        var n = reg2.exec(s);
        return (res+n[1]);
    }
}